import React, {PureComponent} from "react";
import {connect} from "react-redux";
import {Modal, notification} from "antd";
import {
    addLinePriceInCreateModel,
    createLinePrice,
    hideCreateLinePrice,
    queryLinePrice,
    updateLinePriceModel
} from "./actions";
import FormEditor from "../../components/FormEditor";
import {getCurrentOrganization, getPrincipal} from "../../lib/identity";
import {formatDate} from "../../lib/func";
import {search} from "../line/actions";


class CreateLinePriceModal extends PureComponent {

    handleCreateRate = () => {
        const formEditor = this.formEditor.props.form;
        if (formEditor) {
            const {dispatch, modelId, model} = this.props;
            formEditor.validateFieldsAndScroll((err, values) => {
                if (!err) {
                    if (values.originPlace === undefined || values.originPlace === null || values.originPlace.length === 0) {
                        notification.error({
                            message: '请选择线路'
                        });
                        return;
                    }
                    if (values.destPlace === undefined || values.destPlace === null || values.destPlace.length === 0) {
                        notification.error({
                            message: '请选择线路'
                        });
                        return;
                    }
                    values.startDate = formatDate(values.startDate);
                    values.endDate = formatDate(values.endDate);
                    if (modelId === undefined) {
                        dispatch(addLinePriceInCreateModel(values));
                        dispatch(hideCreateLinePrice());
                    } else {
                        dispatch(createLinePrice({
                            ...model,
                            ...values,
                            "feeType": "应收",
                            "belongId": modelId,
                            "organizationId": getCurrentOrganization(),
                            "opId": getPrincipal().id
                        })).then(action => {
                            if (action.error !== true) {
                                dispatch(hideCreateLinePrice());
                                dispatch(queryLinePrice({"belongId": modelId}));
                                notification.success({
                                    message: '创建成功'
                                });
                            }
                        });
                    }
                }
            });
        }
    };
    handleCancel = () => {
        const {dispatch} = this.props;
        dispatch(hideCreateLinePrice());
    };

    changeLine = text => {
        const {dispatch} = this.props;
        dispatch(search({"searchText": text}));
    };

    selectLine = line => {
        const {dispatch, model} = this.props;
        if (line && line.length > 0) {
            const found = line.split("-");
            model.originPlace = found[0];
            model.destPlace = found[1];
            dispatch(updateLinePriceModel(model));
            notification.success({
                message: '切换线路成功'
            });
        }
    };
    handleUpdateModel = model => {
        const {dispatch} = this.props;
        dispatch(updateLinePriceModel(model));
    };

    render() {
        const {loading, visible, model = {pb: 167}, businessList, currencyList, feeList, unitList, calculateType, lineDataList = [], coachList = []} = this.props;
        const feeNames = [];
        feeList.forEach(item => {
            if (item.name !== "报关费" || item.name !== "报关联单费") {
                feeNames.push(item);
            }
        });
        const lineList = [];
        if (model.businessType) {
            lineDataList.forEach(item => {
                if (item.businessType === model.businessType) {
                    lineList.push(item.originPlace + "-" + item.destPlace)
                }
            });
        } else {
            lineDataList.forEach(item => lineList.push(item.originPlace + "-" + item.destPlace));
        }
        const schema = [
            {
                title: '基础信息',
                fields: [
                    {
                        field: 'businessType',
                        title: '业务类型',
                        type: 'listSelector',
                        controlProps: {
                            dataSource: businessList,
                            labelField: "name",
                            valueField: "name"
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择业务类型'}]
                        }
                    }, {
                        field: 'unit',
                        title: '计量单位',
                        type: 'listSelector',
                        controlProps: {
                            dataSource: unitList
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择计量单位'}]
                        }
                    }, {
                        field: 'line',
                        title: '选择线路',
                        type: 'autoComplete',
                        placeholder: "输入城市进行搜索",
                        controlProps: {
                            dataSource: lineList,
                            onChange: this.changeLine,
                            onSelect: this.selectLine
                        }
                    }, {
                        field: 'originPlace',
                        title: '起始站',
                        type: 'text',
                        readonly: true
                        /*fieldOptions: {
                            rules: [{required: true, message: '请输入起始站'}]
                        }*/
                    }, {
                        field: 'destPlace',
                        title: '目的站',
                        type: 'text',
                        readonly: true
                        /*fieldOptions: {
                            rules: [{required: true, message: '请输入目的站'}]
                        }*/
                    }, {
                        field: 'departurePort',
                        title: '出境口岸',
                        type: 'listSelector',
                        controlProps: {
                            dataSource: coachList,
                            labelField: "name",
                            valueField: "name"
                        }
                    }, {
                        field: 'feeName',
                        title: '费用科目',
                        type: 'listSelector',
                        controlProps: {
                            dataSource: feeNames,
                            labelField: "name",
                            valueField: "name"
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择费用科目'}]
                        }
                    }, {
                        field: 'currency',
                        title: '币种',
                        type: 'listSelector',
                        controlProps: {
                            dataSource: currencyList,
                            labelField: "name",
                            valueField: "name"
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择币种'}]
                        }
                    }, {
                        field: 'price',
                        title: '单价/KG',
                        type: 'number',
                        fieldOptions: {
                            rules: [{required: true, message: '请输入重量单价'}]
                        },
                    }, {
                        field: 'price2',
                        title: '单价/CBM',
                        type: 'number',
                        fieldOptions: {
                            rules: [{required: true, message: '请输入体积单价'}]
                        },
                    }, {
                        field: 'pb',
                        title: '重泡比',
                        type: 'formatNumber',
                        controlProps: {
                            formatter: value => "1:" + value,
                            parser: value => value.replace("1:", "")
                        }
                    }, {
                        field: 'calculateType',
                        title: '计费方式',
                        type: 'listSelector',
                        controlProps: {
                            dataSource: calculateType
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择计费方式'}]
                        }
                    }, {
                        field: 'startDate',
                        title: '有效期开始',
                        type: 'date',
                        fieldOptions: {
                            rules: [{required: true, message: '请选择有效期开始'}]
                        },
                    }, {
                        field: 'endDate',
                        title: '有效期结束',
                        type: 'date',
                        fieldOptions: {
                            rules: [{required: true, message: '请选择有效期结束'}]
                        }
                    }, {
                        field: 'remark',
                        title: '备注',
                        type: 'textArea'
                    }
                ]
            }];

        return (
            <Modal
                title="新增"
                visible={visible}
                onOk={this.handleCreateRate}
                onCancel={this.handleCancel}
                confirmLoading={loading}
                okText="保存"
                cancelText="取消"
                width="90%"
            >
                <FormEditor
                    schema={schema}
                    column={3}
                    defaultReadonly={false}
                    showActionBar={false}
                    defaultValues={model}
                    wrappedComponentRef={inst => (this.formEditor = inst)}
                    onChange={this.handleUpdateModel}
                />
            </Modal>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.client.createLinePrice,
        currencyList: state.client.list.currencyList,
        feeList: state.client.list.feeList,
        unitList: state.common.unitList,
        calculateType: state.common.calculateType,
        businessList: state.client.list.businessList,
        transportType: state.client.list.transportType,
        lineDataList: state.line.list.data,
        coachList: state.coach.list.dataSource
    };
};

export default connect(mapStateToProps)(CreateLinePriceModal);
